package com.iiiu.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iiiu.payment.domain.entity.Category;
import com.iiiu.payment.mapper.CategoryMapper;
import com.iiiu.payment.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 分类服务实现类
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public List<Category> getByUserId(Long userId) {
        return baseMapper.selectByUserId(userId);
    }

    @Override
    public Category getByUserIdAndName(Long userId, String name) {
        return baseMapper.selectByUserIdAndCategoryName(userId, name);
    }

    @Override
    public Category createCategory(Category category) {
        // 检查名称是否已存在
        if (existsByUserIdAndName(category.getUserId(), category.getCategoryName())) {
            throw new RuntimeException("分类名称已存在");
        }

        // 设置排序顺序
        if (category.getSortOrder() == null) {
            // 获取当前用户的最大排序值
            LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Category::getUserId, category.getUserId())
                       .eq(Category::getIsDelete, 0)
                       .orderByDesc(Category::getSortOrder)
                       .last("LIMIT 1");
            
            Category lastCategory = getOne(queryWrapper);
            int nextOrder = lastCategory != null ? lastCategory.getSortOrder() + 1 : 1;
            category.setSortOrder(nextOrder);
        }

        category.setIsDelete(0);
        save(category);
        return category;
    }

    @Override
    public Category updateCategory(Category category) {
        Category existingCategory = getById(category.getId());
        if (existingCategory == null) {
            throw new RuntimeException("分类不存在");
        }

        // 检查是否属于当前用户
        if (!existingCategory.getUserId().equals(category.getUserId())) {
            throw new RuntimeException("无权限修改此分类");
        }

        // 检查名称是否重复（排除自己）
        Category duplicateCategory = getByUserIdAndName(category.getUserId(), category.getCategoryName());
        if (duplicateCategory != null && !duplicateCategory.getId().equals(category.getId())) {
            throw new RuntimeException("分类名称已存在");
        }

        // 更新字段
        if (StringUtils.hasText(category.getCategoryName())) {
            existingCategory.setCategoryName(category.getCategoryName());
        }
        if (StringUtils.hasText(category.getIcon())) {
            existingCategory.setIcon(category.getIcon());
        }
        if (StringUtils.hasText(category.getColor())) {
            existingCategory.setColor(category.getColor());
        }
        if (StringUtils.hasText(category.getDescription())) {
            existingCategory.setDescription(category.getDescription());
        }
        if (category.getSortOrder() != null) {
            existingCategory.setSortOrder(category.getSortOrder());
        }

        updateById(existingCategory);
        return existingCategory;
    }

    @Override
    public boolean deleteCategory(Long id, Long userId) {
        Category category = getById(id);
        if (category == null) {
            return false;
        }

        // 检查是否属于当前用户
        if (!category.getUserId().equals(userId)) {
            throw new RuntimeException("无权限删除此分类");
        }

        // 软删除
        category.setIsDelete(1);
        return updateById(category);
    }

    @Override
    public boolean existsByUserIdAndName(Long userId, String name) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getUserId, userId)
                   .eq(Category::getCategoryName, name)
                   .eq(Category::getIsDelete, 0);
        return count(queryWrapper) > 0;
    }

    @Override
    public boolean updateSortOrder(Long userId, List<Long> categoryIds) {
        if (categoryIds == null || categoryIds.isEmpty()) {
            return false;
        }

        try {
            for (int i = 0; i < categoryIds.size(); i++) {
                Long id = categoryIds.get(i);
                Category category = getById(id);
                
                if (category != null && category.getUserId().equals(userId)) {
                    category.setSortOrder(i + 1);
                    updateById(category);
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}